package com.company.learning.thread.demo;


import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zhaoqi
 * @Date: 11/22/2019 10:16 PM
 * @Version 1.0
 */
//两个线程交替打印奇偶数1-100   synchronized 线程池   线程之间通信

public class TwoThread3 {

    private int start = 0;

    private boolean flag =false;



    public static void main(String[] args) {

        LinkedBlockingDeque linkedBlockingDeque = new LinkedBlockingDeque();
        TwoThread3 twoThread2 = new TwoThread3();
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 15, 10L, TimeUnit.SECONDS,linkedBlockingDeque);
        poolExecutor.execute(new TwoThread3.OuNum(twoThread2));
        poolExecutor.execute(new TwoThread3.JiNum(twoThread2));


        poolExecutor.shutdown();
    }

    public static class OuNum implements Runnable{

        private TwoThread3 number;

        OuNum(TwoThread3 number) {
            this.number = number;
        }

        @Override
        public void run() {
            while (number.start <=100){
                synchronized (TwoThread3.class){
                    System.out.println("偶数抢到线程！");
                    if (number.flag){
                        System.out.println(Thread.currentThread().getName() + "--------------" + number.start);
                        number.start++;
                        number.flag =false;
                        TwoThread3.class.notify();
                    }else {
                        //防止线程空转
                        try {
                            TwoThread3.class.wait();
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
    }

    public static class JiNum implements Runnable{

        private TwoThread3 number;

        JiNum(TwoThread3 number) {
            this.number = number;
        }

        @Override
        public void run() {
            while (number.start <=100){
                synchronized (TwoThread3.class){
                    System.out.println("奇数抢到线程！");
                    if (!number.flag){
                        System.out.println(Thread.currentThread().getName() + "++" + number.start);
                        number.start++;
                        number.flag =true;
                        TwoThread3.class.notify();
                    }else {
                        //防止线程空转
                        try {
                            TwoThread3.class.wait();
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

}
